<template>
  <el-upload

    class="avatar-uploader"
    action="#"
    :http-request="upload"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-if="showProgres" :src="imgUrl" class="avatar-pic" type="circle" :percentage="percentage" />
  </el-upload>
</template>

<script>
// 引入必要的COS模块
const COS = require('cos-js-sdk-v5')
// 实例化对象
const cos = new COS({
  SecretId: 'AKIDhCTVHo57tPghTzGH3arseATWNzLwIPGs', // 身份识别ID
  SecretKey: 'RdZGhwwgBQQAettd7LK3XljSv97qJWUD' // 身份秘钥
})
export default {
  props: {
    imgUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      percentage: 0,
      showProgres: false
    }
  },
  // 监听父传子的imgUrl改变了就赋值给当前的imageUrl
  watch: {
    imgUrl() {
      this.imageUrl = this.imgUrl
    }
  },
  methods: {
    // 图片上传前的钩子
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 自定义上传行为
    upload(fileData) {
      this.showProgres = true
      // fileData.file 存放着文件对象
      // 调用三方服务器的接口上传头像了
      cos.putObject({
        Bucket: 'likang-1311503705', /* 存储桶 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: fileData.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: fileData.file, // 上传文件对象

        onProgress: (progressData) => {
          // 上传中不断执行
          console.log(JSON.stringify(progressData))
          this.percentage = parseInt(progressData.percent * 100)
        }
      }, (err, data) => {
        // 上传完毕执行
        console.log(err || data)
        // console.log('上传头像', data)
        if (data.statusCode === 200) {
          // 回显图片
          this.imageUrl = `http://${data.Location}`
          // 抛给父元素url地址
          this.$emit('update-url', this.imageUrl)
          this.showProgres = false
        }
        data.Location
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-pic{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
  }
</style>
